import axios from "axios";
import { useUserInfo } from "../store/userInfo";
import { ElMessage } from "element-plus";
import { AxiosResp, Resp, User } from "../model/Model";
import router from "@/router/router";

const _axios = axios.create({
    baseURL: import.meta.env.VITE_BACKEND_API_BASE_URL,
    timeout: 5000
})

_axios.interceptors.request.use(
    (config) => {
        if (useUserInfo().getterToken) {
            config.headers["Authorization"] = useUserInfo().getterToken
        }
        return config
    },
    (error) => {
        return Promise.resolve(error)
    }
)

_axios.interceptors.response.use(
    (response: AxiosResp<Resp<User>>) => {
        const code = response.data.code
        const msg = response.data.message || ""
        if (response.status && response.status === 200) {
            if (code) {
                if (code.toString().endsWith('1')) {
                    ElMessage.success(msg)
                } else if (code.toString().endsWith('0')) {
                    ElMessage.warning(msg)
                } else if (code === 2999) {
                    const msgList = msg.split('!')
                    for (const msg of msgList) {
                        if (msg) {
                            ElMessage.warning(msg)
                        }
                    }
                } else if (code === 40001) {
                    useUserInfo().clearUserInfo
                    router.push('/login')
                    ElMessage.warning(msg)
                } else {
                    ElMessage.error(msg)
                }
            }
        }
        return response
    },
    (error) => {
        return Promise.resolve(error)
    }
)

export default _axios